<template>
  <a-drawer
    :title='title'
    :width='width'
    placement='right'
    :closable='false'
    :visible='visible'
    @close='onClose'
  >
    <a-form :form='form'>
      <a-row :gutter='24'>
        <a-col :md='18' :sm='24'>
          <a-form-item label='用户' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-input :disabled='true' placeholder='用户' v-decorator="['roleCode', validatorRules.roleCode]" />
          </a-form-item>
        </a-col>
        <a-col :md='18' :sm='24'>
          <a-form-item label='姓名' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-input :disabled='true' placeholder='姓名' v-decorator="['roleName', validatorRules.roleName]" />
            <a-input type='hidden' :disabled='true' placeholder='所属菜单'
                     v-decorator="['functionCode', validatorRules.functionCode]" />
          </a-form-item>
        </a-col>
        <a-col :md='18' :sm='24'>
          <a-form-item label='权限对象' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <cn-dict-select-tag
              :options="{ value: 'dictDataCode', label: 'dictDataDesc' }"
              :triggerChange='true'
              dictCode='perms_type'
              v-decorator="['dataType', validatorRules.dataType]"
              placeholder='请选择对象'
              @change='cataChange'
            />
            <div v-if='showChoice'>
              <!--              <a-input-search v-model='appoints.code'-->
              <!--                              ></a-input-search>-->
              <!--              <a-input v-model='appoints.name'></a-input>-->
              <div style='display: flex'>

                <div style='min-height: 50px;width: 100%;border: 1px solid skyblue'>
                  <a-tag v-for='(item,index) in appoints' :key='index' :value='item.code'>
                    {{ item.name }}
                  </a-tag>
                </div>
                <a-button type='primary' @click='methodway == 1 ? productSearch("userName") : custSearch("orgCode")'>
                  请选择
                </a-button>
              </div>


            </div>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <proChose ref='prochoose' @okbro='okbropro'></proChose>
    <!--    底部取消\确认按钮-->
    <div
      :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
    >
      <a-button :style="{ marginRight: '8px' }" @click='onClose'>
        取消
      </a-button>
      <a-button type='primary' @click='handOk'>
        确认
      </a-button>
    </div>
  </a-drawer>
</template>

<script>
import type from '@views/exception/type'
import { getAction, postAction } from '@/api/manage'
import { PageListMixin } from '@/mixins/PageListMixin'
import proChose from '@comp/cn-components/ProChose'
import { pick } from 'lodash'
import moment from 'moment'

export default {
  name: 'DataPermissionModal',
  description: '数据权限配置',
  mixins: [PageListMixin],
  components: { proChose },
  props: {
    tableShowSelect: {
      type: Boolean,
      default: true
    },
    haveSelect: {
      type: Object
    },
    title: {
      type: String,
      default: '权限对象新增'
    },
    width: {
      type: String || number,
      default: '40%'
    },
    rowKey: {
      type: String,
      default: 'id'
    },
    way: {
      type: String,
      default: 'get'
    },
    tableUrl: {
      type: String,
      default: 'get'
    },
    tableColums: {
      type: Array
    },
    multiple: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      model: {},
      methodway: '',
      showChoice: false,
      appoints: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      form: this.$form.createForm(this),
      selectedRowKeys: [],
      selectionRows: [],
      visible: false,
      url: {
        list: null
      },
      dataSource: [],
      validatorRules: {
        dataType: {
          rules: [{ required: true, message: '' }]
        }
      },
      url: {
        sendOrder: window._CONFIG['domianURL'] + '/sysDataPermsController/saveOrUpdate'
      }
    }
  },
  methods: {
    okbropro(e1, e2) {
      console.log(e1, e2)
      let array = []
      if (e2 == 'userName') {
        e1.forEach(item => {
          let obj = {
            code: item.userName,
            name: item.realName
          }
          array.push(obj)
        })
      } else if (e2 == 'orgCode') {
        e1.forEach(item => {
          let obj = {
            code: item.orgCode,
            name: item.orgName
          }
          array.push(obj)
        })
      }
      this.$set(this, 'appoints', array)
      console.log(this.appoints)
    },
    custSearch(status) {
      this.$refs.prochoose.rowKey = 'orgCode'
      let formconfig = [
        {
          key: 'orgCode',
          label: '组织编号'
        },
        {
          key: 'orgName',
          label: '组织名称'
        }
      ]
      let tableconfig = {
        columns: [
          {
            title: '组织编号',
            align: 'center',
            dataIndex: 'orgCode',
            width: 120,
            ellipsis: true
          },
          {
            title: '组织名称',
            align: 'center',
            dataIndex: 'orgName',
            width: 120,
            ellipsis: true
          }
        ],
        list: window._CONFIG['domianURL'] + '/cnOrgController/findTreeList',
        multiple: true,
        columW: 11
      }
      let dataSource = []
      if (this.form.getFieldValue('custCode')) {
        dataSource = [{
          custCode: this.form.getFieldValue('orgCode'),
          custName: this.form.getFieldValue('orgName')
        }]
      }
      this.name = '经销商'
      this.$refs.prochoose.edit(formconfig, tableconfig, status, 'status2', dataSource)
    },
    // 用户
    productSearch(status) {
      this.$refs.prochoose.rowKey = 'id'
      let formconfig = [
        {
          key: 'realName',
          label: '用户账户'
        },
        {
          key: 'userName',
          label: '用户名称'
        }
      ]
      let tableconfig = {
        columns: [
          {
            title: '用户账户',
            align: 'left',
            dataIndex: 'realName',
            width: 120,
            ellipsis: true
          },
          {
            title: '用户名称',
            align: 'left',
            dataIndex: 'userName',
            width: 120,
            ellipsis: true
          }
        ],
        list: window._CONFIG['domianURL'] + '/cnUserController/getPageList',
        multiple: true,
        columW: 10
      }
      this.name = '用户'
      let dataSource = []
      if (this.form.getFieldValue('superiorUser')) {
        dataSource = [{
          userName: this.form.getFieldValue('superiorUser'),
          realName: this.form.getFieldValue('realsname')
        }]
      }
      console.log(dataSource)
      this.$refs.prochoose.edit(formconfig, tableconfig, status, 'realsname', dataSource)
    },
    cataChange(e1, e2) {
      if (e2.dictCode == 'perms_type') {
        this.showChoice = false
        this.methodway = null
        if (e2.dictDataCode == 6) {
          this.productSearch('userName')
          this.methodway = 1
          this.form.setFieldsValue({
            dataType: null
          })
          this.showChoice = true
          return
        } else if (e2.dictDataCode == 7) {
          this.custSearch('orgCode')
          this.methodway = 2
          this.form.setFieldsValue({
            dataType: null
          })
          this.showChoice = true
          return
        }
        this.form.setFieldsValue({
          dataType: e2.dictDataCode
        })
      }
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      console.log(this.ipagination)
      this.loadData()
    },
    loadData(arg) {
      if (!this.url || !this.url.list) {
        // this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }

      var params = this.getQueryParams()//查询条件
      this.loading = true
      let request = null
      const isNoPagnation = ['getDictByCode'].some(url => new RegExp(`${url}$`).test(this.url.list))
      if (isNoPagnation) {
        request = getAction
      } else {
        request = postAction
      }
      var that = this
      return request(this.url.list, params).then((res) => {
        if (res.success) {
          if (res.result.records) {
            that.dataSource = res.result.records
          } else {
            that.dataSource = res.result
          }
          that.ipagination.total = res.result.total || 0
        } else {
          that.$message.warning(res.message)
        }
        that.loading = false
      })
      // }
    },
    //TODO params 请求地址数据体， key必要时的关键字，
    edit(params) {
      console.log(params)
      this.visible = true
      this.model = Object.assign({}, params)
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(params, 'roleName', 'roleCode', 'functionCode'))
      })

    },
    handOk() {
      let _vm = this
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true
          values = Object.assign({}, values)
          values.appoints = [this.appoints]
          postAction(this.url.sendOrder, values).then(res => {
            if (!res.success) {
              this.$message.error(res.message)
              this.$emit('polocyOk', this.model)
            } else {
              this.$emit('polocyOk', this.model)
            }
            this.onClose()
          })
        }
      })
    },
    onClose() {
      this.queryParam = {}
      this.selectionRows = []
      this.selectedRowKeys = []
      this.visible = false
    },
    /** 删除已选择的 */
    handleDeleteSelected(record, index) {
      this.selectedRowKeys.splice(this.selectedRowKeys.indexOf(record[this.rowKey]), 1)
      this.selectionRows.splice(index, 1)
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    customRowFn(record, e2) {
      return {
        on: {
          click: () => {
            let key = record[this.rowKey]
            if (!this.multiple) {
              this.selectedRowKeys = [key]
              this.selectionRows = [record]
              // this.selectedTable.dataSource = [record]
            } else {
              let index = this.selectedRowKeys.indexOf(key)
              if (index === -1) {
                this.selectedRowKeys.push(key)
                this.selectionRows.push(record)
                // this.selectedTable.dataSource.push(record)
              } else {
                this.handleDeleteSelected(record, index)
              }
            }
          }
        }
      }
    }
  }
}
</script>

<style scoped>

</style>